package com.bjy.qa.agent;

import com.bjy.qa.agent.tools.resttemplate.LoggerRequestInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * springboot 主入口
 */
@SpringBootApplication
public class QaPlatformAgentApplication {
	@Value("${qap.rest-template.debug:false}")
	private Boolean restTemplateDebug;

	public static void main(String[] args) {
		SpringApplication.run(QaPlatformAgentApplication.class, args);
	}

	@Bean
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		if (restTemplateDebug) {
			// TODO: 2024/2/27 这里给 restTemplate 添加了日志拦截器，有可能会有 bug，临时保留
			RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); // 默认 SimpleClientHttpRequestFactory 只能读一次 body。这里 日志拦截器 也需要读取 body，所以要使用 BufferingClientHttpRequestFactor
			List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
			interceptors.add(new LoggerRequestInterceptor()); // 添加日志拦截器（debug）
			restTemplate.setInterceptors(interceptors);
			return restTemplate;
		} else {
			return builder.build();
		}
	}
}
